<?php

namespace App\Http\Controllers\Pc;

use App\Http\Requests\ProductSku\AddLazadaSkuRequest;
use App\Http\Requests\ProductSku\AddVovaSkuRequest;
use App\Http\Requests\ProductSku\AddWishSkuRequest;
use App\Libs\platformApi\Lazada;
use App\Libs\wrapper\Vova;
use App\Libs\wrapper\Wish;
use App\Models\ProductSkuModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class ProductSkuController extends Controller
{
    private $model;
    private $request;

    public function __construct(Request $request)
    {
        $this->model = new ProductSkuModel;
        $this->request = $request;
    }

    /**
     * wish 子sku列表
     */
    public function getWishSkuList() {
        $this->validate($this->request, [
            'product_id' => 'required| numeric'
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误'
        ]);
        $params = $this->request->all();
        $result = $this->model->getWishChildSkuList($params);
        return $this->back('获取成功', '200', $result);
    }

    //wish更新
    public function updateWish(){
        $this->validate($this->request, [
            'product_id' => 'required| numeric',
            'inventory' => 'required| numeric',
            'price' => 'required| numeric',
            'shipping' => 'required| numeric',
        //    'color' => 'required| string',
            'size' => 'required| string',
            'image' => 'required| string',
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
            'inventory.required' => '请填写库存',
            'inventory.numeric' => '库存必须是数字',
            'price.required' => '请填写价格',
            'price.numeric' => '价格必须是数字',
            'shipping.required' => '请填写邮费',
            'shipping.numeric' => '邮费必须是数字',
//            'color.required' => '请填写color',
//            'color.string' => 'color必须是字符串',
            'size.required' => '请填写size',
            'size.string' => 'size必须是字符串',
            'image.required' => '请上传产品图',
            'image.string' => '产品图链接必须是字符串',
        ]);
        $params = $this->request->all();
        //先查询父sku基本信息
        $productId = $params['product_id'];
        $sql = "SELECT
                    p.shop_id,
                    p.product_id_pt,
                    ps.goods_sku,
                    ps.price,
                    ps.storage,
                    ps.shipping_fee,
                    ps.size,
                    ps.color,
                    ps.main_image 
                FROM
                    product_sku ps
                    JOIN product p ON ps.product_id = p.Id 
                WHERE
                    ps.Id = $productId 
                    LIMIT 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $shopId = $product->shop_id;
        //查询access_token
        $sql = "select Id,access_token from shop where Id = $shopId limit 1";
        $shop = DB::select($sql);
        if (empty($shop)) {
            return $this->back('根据商户id查询没有结果~,请检查商户id');
        }
        $accessToken = $shop[0]->access_token;
        $price = $params['price'];
        $inventory = $params['inventory'];
        $shipping = $params['shipping'];
      //  $color = $params['color'];
        $size = $params['size'];
        $image = $params['image'];
        $sku = $product->goods_sku;
        $obj = new \App\Libs\platformApi\Wish();
        $errors = [];
        //价格 库存 尺码 颜色  . $product->color  . $color
        if (md5($product->price . $product->storage . $product->size  . $product->main_image)
            != md5(($price * 100) . $inventory . $size . $image)){
            $result = $obj->updateVariant($accessToken, $sku, $price, $inventory, '', $size, $image);
            if (isset($result['code']) && $result['code'] == 0) {
                DB::beginTransaction();
                try{
                    //color = '$color',
                    $price *= 100;
                    $sql = "update product_sku 
                            set 
                                price = $price,storage = $inventory,`size` = '$size',main_image='$image' 
                            where 
                                Id = $productId";
                    DB::update($sql);
                    DB::commit();
                }catch (\Exception $e) {
                    DB::rollBack();
                    $errors['SqlError'][] = $e->getMessage();
                }
            } else {
                $errors['platformError'][] = $result['message'];
            }
        }
        //邮费
        if (md5($product->shipping_fee) != md5($shipping * 100)){
            $result = $obj->updateShipping($accessToken,$product->product_id_pt,$shipping);
            if (isset($result['code']) && $result['code'] == 0) {
                DB::beginTransaction();
                try{
                    $shipping *= 100;
                    $sql = "update product_sku set shipping_fee = $shipping where Id = $productId";
                    DB::update($sql);
                    DB::commit();
                }catch (\Exception $e) {
                    DB::rollBack();
                    $obj->updateShipping($accessToken,$product->product_id_pt,$product->shipping_fee/100);
                    $errors['SqlError'] = $e->getMessage();
                }
            } else {
                $errors['platformError'] = $result['message'];
            }
        }

        if (empty($errors)) {
            return $this->back('更新成功',200);
        }
        return $this->back($errors);
    }
    //vova编辑sku
//    public function vovaUpdateSku(){
//        $this->validate($this->request, [
//            'product_sku_id' => 'required| numeric',
//            'price' => 'required| numeric',
//            'shipping_fee' => 'required| numeric',
//            'storage' => 'required| numeric'
//        ], [
//            'product_sku_id.required' => '缺少product_sku_id参数',
//            'product_sku_id.numeric' => 'product_sku_id类型错误',
//            'price.required' => '缺少price参数',
//            'price.numeric' => 'price类型错误',
//            'shipping_fee.required' => '缺少shipping_fee参数',
//            'shipping_fee.numeric' => 'shipping_fee类型错误',
//            'storage.required' => '缺少storage参数',
//            'storage.numeric' => 'storage类型错误'
//        ]);
//        $params = $this->request->all();
//        //先查询父sku基本信息
//        $productSkuId = $params['product_sku_id'];
//        $sql = "SELECT
//                    p.shop_id,
//                    p.product_id_pt,
//                    ps.goods_sku,
//                    ps.price,
//                    ps.storage,
//                    ps.shipping_fee,
//                    ps.size,
//                    ps.color,
//                    s.access_token
//                FROM
//                    product_sku ps
//                    JOIN product p ON ps.product_id = p.Id
//                    JOIN shop s ON s.Id = p.shop_id
//                WHERE
//                    ps.Id = $productSkuId
//                    LIMIT 1";
//        $product = DB::select($sql);
//        if (empty($product)) {
//            return $this->back('根据产品id查询没有结果~,请检查产品id');
//        }
//        $product = $product[0];
//        $price = $params['price'] * 100;
//        $shippingFee = $params['shipping_fee'] * 100;
//        $storage = $params['storage'];
//        if (md5($product->price . $product->storage . $product->shipping_fee)
//            != md5($price . $storage . $shippingFee)) {
//            $obj = new \App\Libs\platformApi\Vova();
//            $updateParams = [
//                'product_id' => $product->product_id_pt,
//                //子商品sku
//                'goods_sku' => $product->goods_sku,
//                'attrs' => [
//                    'shop_price' => $price / 100,
//                    'shipping_fee' => $shippingFee / 100,
//                    'storage' => $storage
//                ]
//            ];
//            $result = $obj->updateGoodsData($product->access_token,$updateParams,null);
//            if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
//                DB::beginTransaction();
//                try{
//                    $sql = "update product_sku set price = $price,storage = $storage,shipping_fee = $shippingFee where Id = $productSkuId";
//                    DB::update($sql);
//                    DB::commit();
//                }catch (\Exception $e) {
//                    DB::rollBack();
//                    $errors['SqlError'][] = $e->getMessage();
//                }
//            } else {
//                $errors['platformError'][] = $result['message'];
//            }
//        }
//        if (empty($errors)) {
//            return $this->back('更新成功',200);
//        }
//
//        return $this->back($errors);
//    }
    //vova编辑sku
    public function vovaUpdateSku(){
        $this->validate($this->request, [
            'product_sku_id' => 'required| numeric',
            'price' => 'required| numeric',
            'shipping_fee' => 'required| numeric',
            'storage' => 'required| numeric',
            'new_sku' => 'required| string',
        ], [
            'product_sku_id.required' => '缺少product_sku_id参数',
            'product_sku_id.numeric' => 'product_sku_id类型错误',
            'price.required' => '请输入价格',
            'price.numeric' => 'price类型错误',
            'shipping_fee.required' => '请输入运费价格',
            'shipping_fee.numeric' => 'shipping_fee类型错误',
            'storage.required' => '请输入库存数量',
            'storage.numeric' => 'storage类型错误',
            'new_sku.required' => '请输入sku',
            'new_sku.string' => 'new_sku类型错误',
        ]);
        $params = $this->request->all();
        //先查询父sku基本信息
        $productSkuId = $params['product_sku_id'];
        $sql = "SELECT
                    p.shop_id,
                    p.product_id_pt,
                    ps.goods_sku,
                    ps.price,
                    ps.storage,
                    ps.shipping_fee,
                    ps.size,
                    ps.color,
                    s.access_token 
                FROM
                    product_sku ps
                    JOIN product p ON ps.product_id = p.Id 
                    JOIN shop s ON s.Id = p.shop_id
                WHERE
                    ps.Id = $productSkuId 
                    LIMIT 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $price = $params['price'] * 100;
        $shippingFee = $params['shipping_fee'] * 100;
        $storage = $params['storage'];
        $newSku = $params['new_sku'];
        if (md5($product->price . $product->storage . $product->shipping_fee . $product->goods_sku)
            != md5($price . $storage . $shippingFee . $newSku)) {
            $obj = new \App\Libs\platformApi\Vova();
            $updateParams = [
                'product_id' => $product->product_id_pt,
                //子商品sku
                'goods_sku' => $product->goods_sku,
                'attrs' => [
                    'shop_price' => $price / 100,
                    'shipping_fee' => $shippingFee / 100,
                    'storage' => $storage
                ]
            ];
            $result = $obj->updateGoodsData($product->access_token,$updateParams,null);
            if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
                DB::beginTransaction();
                try{
                    $sql = "update product_sku set price = $price,storage = $storage,shipping_fee = $shippingFee where Id = $productSkuId";
                    DB::update($sql);
                    DB::commit();
                }catch (\Exception $e) {
                    DB::rollBack();
                    $errors['SqlError'][] = $e->getMessage();
                }
            } else {
                $errors['platformError'][] = $result;
            }
            $params = [
                'product_id' => $product->product_id_pt,
                'type' => 'sku',
                //旧的子sku，注意：更新子sku时，才有这个属性，如 [‘goods_id’ => ‘’,’type’ => ‘sku’,’goods_sku’ => ‘’,’new_sku’ => ‘’,’parent_sku’ => ‘’]
                'goods_sku' => $product->goods_sku,
                //新的子sku，注意：更新子sku时，才有这个属性
                'new_sku' => $params['new_sku']
            ];
            $result = $obj->updateGoodsData($product->access_token,[],$params);
            if (isset($result['execute_status']) && $result['execute_status'] == 'success') {
                DB::beginTransaction();
                try{
                    $sql = "update product_sku set goods_sku = '$newSku' where Id = $productSkuId";
                    DB::update($sql);
                    DB::commit();
                }catch (\Exception $e) {
                    DB::rollBack();
                    $errors['SqlError'][] = $e->getMessage();
                }
            } else {
                $params['goods_sku'] = $newSku;
                $params['new_sku'] = $product->goods_sku;
                $obj->updateGoodsData($product->access_token,[],$params);
                $errors['platformError'][] = $result;
            }
        }
        if (empty($errors)) {
            return $this->back('更新成功',200);
        }

        return $this->back($errors);
    }

    //lazada平台sku上传图片
    public function lazadaSkuUploadImage(){
        $this->validate($this->request, [
            'product_id' => 'required| numeric'
        ], [
            'product_id.required' => '缺少product_id参数',
            'product_id.numeric' => 'product_id类型错误',
        ]);
        $params = $this->request->all();
        if (!$this->request->hasFile('image')) {
            return $this->back('请上传至少一张图片');
        }
        $file = $this->request->file('image');
        $extensionArray = ['jpg','bmp','gif','png','jpeg'];
        //检查文件后缀
        foreach ($file as $v) {
            $extension = $v->extension();
            if (!in_array($extension,$extensionArray)) {
                return $this->back('图片上传只支持后缀' . implode(',',$extensionArray) . ',请检查上传的图片');
            }
        }
        $lazadaObj = new Lazada();
        $productId = $params['product_id'];
        //查询token
        $sql = "select s.access_token from product p join shop s on p.shop_id = s.Id where p.Id = $productId limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $accessToken = $product->access_token;

        $result = [];
        $errors = [];
        foreach ($file as $v) {
            //上传图片
            $res = $lazadaObj->uploadImage($accessToken,$v);
            if (isset($res['code']) && $res['code'] == '0') {
                $result[] = $res['data']['image']['url'];
            } else {
                $errors[] = $res;
            }
        }
        if (empty($errors)) {
            return $this->back('成功上传图片' . count($result) . '张!',200,$result);
        }
        return $this->back($errors);
    }

    //lazada sku编辑
    public function lazadaSkuUpdate(){
        $this->validate($this->request, [
            'product_sku_id' => 'required|numeric',
            'quantity' => 'required|numeric',
            'price' => 'required|numeric',
            'image' => 'required'
        ], [
            'product_sku_id.required' => '缺少product_sku_id参数',
            'product_sku_id.numeric' => 'product_sku_id类型错误',
            'quantity.required' => '请输入库存数量',
            'quantity.numeric' => '类型quantity错误',
            'price.required' => '请输入价格',
            'price.numeric' => '类型price错误',
            'image.required' => '请上传图片'
        ]);
        $params = $this->request->all();
        $productSkuId = $params['product_sku_id'];
        $sql = "select p.product_id_pt,ps.goods_sku,ps.price,ps.storage,s.access_token,ps.all_images 
                from product_sku ps
                join product p on ps.product_id = p.Id
                join shop s on p.shop_id = s.Id
                where ps.Id = $productSkuId
                limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];
        $quantity = $params['quantity'];
        $price = $params['price'] * 100;
        $image = $params['image'];
        $imageStr = implode(',',$image);


        if (md5($product->price . $product->storage . $product->all_images)
            == md5($price . $quantity . $imageStr)) {
            return $this->back('更改成功',200);
        }
        $accessToken = $product->access_token;
        $platformProductId = $product->product_id_pt;
        $goodsSku = $product->goods_sku;
        $obj = new Lazada();
        $result = $obj->updateSkuProduct($accessToken, $platformProductId,$goodsSku, $quantity, $price / 100, $image);
        $errors = [];
        if (isset($result['code']) && $result['code'] == 0) {
            DB::beginTransaction();
            try {
                $sql = "update product_sku set `storage` = $quantity,`price` = $price,`all_images` = '$imageStr' where Id = $productSkuId";
                DB::update($sql);
                DB::commit();
            }catch (\Exception $e) {
                DB::rollBack();
                $errors['SqlError'][] = $e->getMessage();
            }
        } else {
            $errors['platformError'][] = $result;
        }
        if (empty($errors)) {
            return $this->back('更新成功',200);
        }
        return $this->back($errors);
    }

    //添加lazada sku
    public function addLazadaSku(AddLazadaSkuRequest $request){
        $params = $request->all();
        $productSkuId = $params['product_sku_id'];
        $sellerSku = $params['seller_sku'];
        $quantity = $params['quantity'];
        $price = $params['price'] * 100;
        $image = $params['image'];
        $color = $params['color'];
        $packageLength = $params['package_length'];
        $packageHeight = $params['package_height'];
        $packageWeight = $params['package_weight'];
        $packageWidth = $params['package_width'];
        $size = $params['size'];

        $sql = "select p.cat_id,ps.product_id,ps.goods_sku,ps.price,ps.storage,s.access_token,ps.all_images 
                from product_sku ps
                join product p on ps.product_id = p.Id
                join shop s on p.shop_id = s.Id
                where ps.Id = $productSkuId
                limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品sku id查询没有结果~,请检查产品sku id');
        }
        $product = $product[0];
        $accessToken = $product->access_token;
        $catId = $product->cat_id;
        $otherSku = $product->goods_sku;
        $productId = $product->product_id;

        //查询要添加的sku是否存在
        $sql = "select * from product_sku where goods_sku = '$sellerSku' and product_id = $productId limit 1";
        $productSku = DB::select($sql);
        if (!empty($productSku)) {
            return $this->back("sku名称:'$sellerSku'已经存在,请更换个名称再添加");
        }

        $imageStr = implode(',',$image);
        $obj = new Lazada();
        DB::beginTransaction();
        try {
            //记录到表中
            $sql = "insert into product_sku (`product_id`,`goods_sku`,`price`,`storage`,`main_image`,`all_images`, `color`, `size`, `state`)
                    values ($productId, '$sellerSku', $price, $quantity, '$image[0]', '$imageStr', '$color', $size, 'active')";
            DB::insert($sql);
            //添加到店铺商品内
            $result = $obj->addSku($accessToken, $catId, $otherSku, $sellerSku, $quantity, $price/100, $image, $color, $size
                                    ,$packageLength, $packageHeight, $packageWeight, $packageWidth);
            if (!isset($result['code']) || $result['code'] != '0') {
                DB::rollBack();
                $errors['platformError'][] = $result;
            } else {
                DB::commit();
            }
        }catch (\Exception $e) {
            DB::rollBack();
            $errors['SqlError'][] = $e->getMessage();
        }
        if (empty($errors)) {
            return $this->back('添加成功',200);
        }
        return $this->back($errors);
    }

    //vova添加sku
    public function addVovaSku(AddVovaSkuRequest $request){
        $params = $request->all();
        $productId = $params['product_id'];
        $sellerSku = $params['seller_sku'];
        $quantity = $params['quantity'];
        $price = $params['price'] * 100;
        $image = $params['image'];
        $color = $params['color'];
        $size = $params['size'];
        $shippingFee = $params['shipping_fee'] * 100;
        //查询要添加的sku是否存在
        $sql = "select * from product_sku where goods_sku = '$sellerSku' and product_id = $productId limit 1";
        $productSku = DB::select($sql);
        if (!empty($productSku)) {
            return $this->back("sku名称:'$sellerSku'已经存在,请更换个名称再添加");
        }

        $sql = "select s.access_token,p.product_name
                from product p
                join shop s on p.shop_id = s.Id
                where p.Id = $productId
                limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];

        $accessToken = $product->access_token;
        $productName = $product->product_name;
        $obj = new \App\Libs\platformApi\Vova();
        DB::beginTransaction();
        try {
            //记录到表中
            $sql = "insert into product_sku (`product_id`,`goods_sku`,`price`,`storage`,`main_image`,`all_images`, `color`, `size`, `state`)
                    values ($productId, '$sellerSku', $price, $quantity, '$image', '$image', '$color', $size, 'active')";
            DB::insert($sql);
            //添加到店铺商品内
            $result = $obj->addSku($accessToken, $productName, $sellerSku, $quantity, $price/100, $shippingFee/100, $size, $color, $image);
            if (!isset($result['execute_status']) || $result['execute_status'] != 'success') {
                DB::rollBack();
                $errors['platformError'][] = $result;
            } else {
                DB::commit();
            }
        }catch (\Exception $e) {
            DB::rollBack();
            $errors['SqlError'][] = $e->getMessage();
        }
        if (empty($errors)) {
            return $this->back('添加成功',200);
        }
        return $this->back($errors);
    }

    //wish添加sku
    public function addWishSku(AddWishSkuRequest $request){
        $params = $request->all();
        $productId = $params['product_id'];
        $sellerSku = $params['seller_sku'];
        $quantity = $params['quantity'];
        $price = $params['price'] * 100;
        $color = $params['color'];
        $size = $params['size'];
        $image = $params['image'];
        //查询要添加的sku是否存在
        $sql = "select * from product_sku where goods_sku = '$sellerSku' and product_id = $productId limit 1";
        $productSku = DB::select($sql);
        if (!empty($productSku)) {
            return $this->back("sku名称:'$sellerSku'已经存在,请更换个名称再添加");
        }

        $sql = "select s.access_token,p.parent_sku
                from product p
                join shop s on p.shop_id = s.Id
                where p.Id = $productId
                limit 1";
        $product = DB::select($sql);
        if (empty($product)) {
            return $this->back('根据产品id查询没有结果~,请检查产品id');
        }
        $product = $product[0];

        $accessToken = $product->access_token;
        $parentSku = $product->parent_sku;
        $obj = new \App\Libs\platformApi\Wish();
        DB::beginTransaction();
        try {
            //记录到表中
            $sql = "insert into product_sku (`product_id`,`goods_sku`,`price`,`storage`,`main_image`,`all_images`, `color`, `size`, `state`)
                    values ($productId, '$sellerSku', $price, $quantity, '$image', '$image', '$color', $size, 'active')";
            DB::insert($sql);
            //添加到店铺商品内
            $result = $obj->variantAdd($accessToken, $parentSku, $sellerSku, $quantity, $price/100, $size, $color, $image);
            if (!isset($result['code']) || $result['code'] != '0') {
                DB::rollBack();
                $errors['platformError'][] = $result;
            } else {
                DB::commit();
            }
        }catch (\Exception $e) {
            DB::rollBack();
            $errors['SqlError'][] = $e->getMessage();
        }
        if (empty($errors)) {
            return $this->back('添加成功',200);
        }
        return $this->back($errors);
    }
}
